package com.example.module_motocircle.motocirclesearch

import android.content.Context
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.lib_common.MySocialConfig
import com.example.lib_common.base.BaseFragment
import com.example.lib_common.post.postEvent
import com.example.module_motocircle.R
import com.example.module_motocircle.databinding.FragmentSearchSuggestionsBinding
import com.example.module_motocircle.databinding.LayoutSearchSuggestionItemBinding
import com.example.module_motocircle.model.SearchModelItem
import com.example.module_motocircle.motocircle.MotocircleViewModel
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class SearchSuggestionsFragment : BaseFragment<MotocircleViewModel,FragmentSearchSuggestionsBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.fragment_search_suggestions
    private var mOnlyTopic: Boolean = false
    private val mViewModel:MotocircleViewModel by activityViewModels()
    companion object{
        val TAG: String = SearchSuggestionsFragment::class.java.simpleName
        private const val ONLY_TOPIC = "only_topic"
        fun newInstance(onlyTopic: Boolean) : SearchSuggestionsFragment{
            val args = Bundle()
            args.putBoolean(ONLY_TOPIC,onlyTopic)
            val fragment = SearchSuggestionsFragment()
            fragment.arguments = args
            return fragment
        }
    }
    private val mAdapter by lazy {
        SearchSuggestionAdapter {
            postEvent(SearchSuggestionEvent(it))
        }
    }

    override fun initView() {
        mOnlyTopic = arguments?.getBoolean(ONLY_TOPIC) ?: false
        initAdapter()
    }

    override fun initData() {

    }

    override fun initListener() {

    }
    fun setNewData(list :List<SearchModelItem>){
        if (mOnlyTopic){
            mAdapter.setNewData(list.filter { it.socialType == MySocialConfig.TOPIC })
        }else{
            mAdapter.setNewData(list)
        }
    }
    fun clearData(){
        mAdapter.clearData()
    }
    /**请求状态*/
    fun onLoading() {
        mBinding.tvHint.visibility = View.VISIBLE
        mBinding.lEmpty.visibility = View.GONE
        mBinding.tvHint.text = "搜索中..."
    }

    fun onSuccess(keyword: String) {
        mAdapter.setHighlightWord(keyword)
        mBinding.tvHint.visibility = View.GONE
        mBinding.lEmpty.visibility = View.GONE
        mBinding.tvHint.text = ""
    }

    fun onError(msg: String) {
        mBinding.tvHint.visibility = View.GONE
        mBinding.lEmpty.visibility = View.VISIBLE
        mBinding.tvErrorViewHint.text = msg
    }
    private fun initAdapter(){
        mBinding.rvSuggestion.layoutManager = LinearLayoutManager(requireActivity(),RecyclerView.VERTICAL,false)
        mBinding.rvSuggestion.adapter = mAdapter
    }
    class SearchSuggestionAdapter(private val onClickSuggestionItem: (SearchModelItem) -> Unit):RecyclerView.Adapter<SearchSuggestionViewHolder>(){
        private val suggestionList: MutableList<SearchModelItem> = mutableListOf()
        private lateinit var mContext: Context
        private var highlightWord: String = ""
        fun setNewData(suggestionList: List<SearchModelItem>) {
            this.suggestionList.clear()
            this.suggestionList.addAll(suggestionList)
            notifyDataSetChanged()
        }

        fun clearData() {
            this.suggestionList.clear()
            notifyDataSetChanged()
        }

        fun setHighlightWord(keyword: String) {
            this.highlightWord = keyword
            notifyDataSetChanged()
        }
        override fun onCreateViewHolder(
            parent: ViewGroup,
            viewType: Int
        ): SearchSuggestionViewHolder {
            mContext = parent.context
            val binding = DataBindingUtil.inflate<LayoutSearchSuggestionItemBinding>(LayoutInflater.from(mContext), R.layout.layout_search_suggestion_item, parent, false)
            return SearchSuggestionViewHolder(binding)
        }

        override fun getItemCount(): Int {
            return suggestionList.size
        }

        override fun onBindViewHolder(holder: SearchSuggestionViewHolder, position: Int) {
            val suggestionItem = suggestionList[position]
            if (suggestionItem.socialType == MySocialConfig.TOPIC) {
                handleTopicSuggestion(holder, suggestionItem)
            } else {
                handleHighlightSuggestion(holder, suggestionItem)
            }
            holder.binding.root.setOnClickListener {
                onClickSuggestionItem.invoke(suggestionItem)
            }
        }
        private fun handleTopicSuggestion(holder: SearchSuggestionViewHolder, suggestion: SearchModelItem) {
            val content = String.format("#%s#", suggestion.keyword)
            val spannableStringBuilder = SpannableStringBuilder(content)
            spannableStringBuilder.setSpan(ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.topic)), 0, content.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            holder.binding.tv.text = spannableStringBuilder
        }
        //高亮处理
        private fun handleHighlightSuggestion(holder: SearchSuggestionViewHolder, suggestion: SearchModelItem) {
            //holder.binding.tv.text = JTextUtils.highlight((suggestion.keyword?:"").toString().trim().replace("\r|\n", ""), highlightWord, ContextCompat.getColor(mContext, R.color.color_d8000f))
            holder.binding.tv.text = (suggestion.keyword ?: "").toString().trim().replace("\r|\n", "")
        }
    }
    class SearchSuggestionViewHolder(val binding: LayoutSearchSuggestionItemBinding) : RecyclerView.ViewHolder(binding.root)
}